<template>
	<u-popup :show="show" :round="10" mode="bottom" @close="close" :closeable="true">
		<view class="pay-container">
			<view class="pay-header">选择支付方式</view>
			<view class="pay-amount">
				<view class="yuan">¥</view>
				<view class="money">{{ amount }}</view>
			</view>
			<view class="pay-list">
				<view 
					class="pay-list-item" 
					v-for="(item, index) in filteredPayList" 
					v-if="!isPayMethodDisabled(item)"
					@click="selectPay(item)"
				>
					<view class="pay-item-left">
						<view class="pay-item-name">{{ item.name }}</view>
						<view v-if="item.value === 'wallet'" class="wallet-balance" :class="{ 'insufficient': isWalletInsufficient }">
							可用余额: ¥{{ (walletBalance / 100).toFixed(2) }}
						</view>
					</view>
					<view class="pay-item-check">
						<view class="pay-item-check">
							<image
								:src="selectedPayId === item.id ? '/static/public/checked.png' : '/static/public/unchecked.png'"
								mode="aspectFit" 
								style="width: 32rpx; height: 32rpx;margin:2rpx 10rpx 0 0;"
							/>
						</view>
					</view>
				</view>
			</view>
			<view class="pay-btn" @click="handlePayment">{{ buttonText }}</view>
		</view>
	</u-popup>
</template>

<script>
	export default {
		name: 'payment',
		props: {
			show: {
				type: Boolean,
				default: false
			},
			amount: {
				type: [Number, String],
				default: 0
			},
			orderId: {
				type: [Number, String],
				default: ''
			},
			payOrderId: {
				type: [Number, String],
				default: ''
			},
			isRecharge: {
				type: Boolean,
				default: false
			},
			needRefresh: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				payList: [
					{
						id: 1,
						name: '钱包支付',
						value: 'wallet'
					},
					// #ifdef APP || H5
					{
						id: 2,
						name: '支付宝支付',
						value: 'alipay_app'
					},
					{
						id: 3,
						name: '微信支付',
						value: 'wx_app', // wx_app App支付，wx_lite 小程序支付
					},
					// #endif
					
					// #ifdef MP-WEIXIN
					{
						id: 3,
						name: '微信支付',
						value: 'wx_lite', 
					}
					// #endif
				],
				selectedPayId: 0,
				selectedPayMethod: null,
				walletBalance: 0
			}
		},
		mounted() {
			this.getWalletInfo();
			// this.getPaymentList()
			if (!this.isRecharge) {
				this.$nextTick(() => {
					const walletPayMethod = this.payList.find(item => item.value === 'wallet')
					if (walletPayMethod && !this.isWalletInsufficient) {
						this.selectPay(walletPayMethod)
					}
				})
			}
		},
		computed: {
			isWalletInsufficient() {
				return this.walletBalance < this.amount
			},
			filteredPayList() {
				return this.payList;
			},
			buttonText() {
				if (!this.isRecharge && (this.selectedPayId==1 && this.isWalletInsufficient)) {
					return '立即充值'
				}
				return '立即支付'
			}
		},
		methods: {
			getPaymentList() {
				this.$http_api.userPayWayList({
					appId: 1
				}).then(res => {
					
				})
			},
			close() {
				this.$emit('update:show', false)
				this.$emit('close')
			},
			isPayMethodDisabled(item) {
				if (item.value === 'wallet') {
					return this.isRecharge
				}
				return false
			},
			selectPay(item) {
				if (this.isPayMethodDisabled(item)) {
					if (this.isWalletInsufficient && !this.isRecharge) {
						uni.$u.toast('钱包余额不足')
					}
					return
				}
				this.selectedPayId = item.id
				this.selectedPayMethod = item
			},
			async getWalletInfo() {
				try {
					const res = await this.$http_api.userWallet({})
					this.walletBalance = res.balance
				} catch (error) {
					console.error('获取钱包余额失败:', error)
				}
			},
			handlePayment() {
				if (!this.isRecharge && (this.selectedPayId==1 && this.isWalletInsufficient)) {
					uni.navigateTo({
						url: '/pages/user/wallet/recharge'
					});
					this.close();
					return;
				}

				if (!this.selectedPayMethod) {
					return uni.$u.toast('请选择支付方式')
				}

				// 检查钱包余额是否足够
				if (this.selectedPayMethod.value === 'wallet' && this.walletBalance < this.amount) {
					return uni.$u.toast('钱包余额不足')
				}

				const formData = {
					orderId: this.orderId ,
					payOrderId: this.payOrderId,
					channelCode: this.selectedPayMethod.value,
					channelExtras: {},
				};
				
				if (['wx_pub', 'wx_lite'].includes(this.selectedPayMethod.value)) {
					let userInfo = uni.getStorageSync('userInfo')
					userInfo = JSON.parse(userInfo);
					// 如果获取不到 openId，微信无法发起支付，此时需要引导
					if (!userInfo || !userInfo.openId) {
						this.bindWeixin();
						return;
					}
					formData.channelExtras.openid = userInfo.openId;
				}
				
				this.$http_api.submitOrder(formData).then(res => {
					// 根据支付渠道调用不同的函数
					const payMethod = this.selectedPayMethod.value;
					
					if (payMethod === 'wallet') {
						// 钱包支付直接成功
						this.$emit('payment-success', { orderId: this.orderId });
						// 钱包支付成功后刷新列表
						if (this.needRefresh) {
							this.$emit('refresh-list')
						}
					} else if (payMethod === 'alipay_app') {
						// 支付宝支付
						this.alipay(res);
					} else if (payMethod === 'wx_app' || payMethod === 'wx_lite') {
						// 微信支付（App或小程序）
						this.wechatPay(res);
					}
				}).catch(err => {
					uni.$u.toast('支付发起失败');
					this.$emit('payment-error', err);
				})
			},
			
			// 支付宝支付
			alipay(data) {
				if (!data || !data.displayContent) {
					return uni.$u.toast('获取支付参数错误');
				}
				uni.requestPayment({
					provider: 'alipay',
					orderInfo: data.displayContent, // 直接使用返回的支付参数
					success: (res) => {
						this.$emit('payment-success', { orderId: this.orderId })
						if (this.needRefresh) {
							this.$emit('refresh-list')
						}
					},
					fail: (err) => {
						if (err.errMsg === 'requestPayment:fail [paymentAlipay:62001]user cancel') {
							uni.$u.toast('支付已手动取消');
						} else {
							this.$emit('payment-error', err.errMsg)
						}
					},
				});
			},
			
			// 统一的微信支付函数，处理App和小程序支付
			wechatPay(data) {
				if (!data || !data.displayContent) {
					return uni.$u.toast('获取支付参数错误');
				}
				
				// 解析支付参数
				const payConfig = JSON.parse(data.displayContent);
				
				// 通用的支付配置
				const paymentConfig = {
					provider: 'wxpay',
					timeStamp: payConfig.timeStamp,
					nonceStr: payConfig.nonceStr,
					package: payConfig.packageValue,
					signType: payConfig.signType,
					paySign: payConfig.paySign,
					success: (res) => {
						this.$emit('payment-success', { orderId: this.orderId })
						if (this.needRefresh) {
							this.$emit('refresh-list')
						}
					},
					fail: (err) => {
						if (err.errMsg === 'requestPayment:fail cancel') {
							uni.$u.toast('支付已手动取消');
						} else {
							this.$emit('payment-error', err.errMsg)
						}
					}
				};
				
				// 调用统一的支付接口
				uni.requestPayment(paymentConfig);
			},
			
			// 绑定微信
			bindWeixin() {
				uni.showModal({
					title: '微信支付',
					content: '请先绑定微信再使用微信支付',
					success: res => {
						if (res.confirm) {
							// #ifdef MP-WEIXIN
							// 微信小程序平台
							this.handleWechatAuth(34, 'default'); 
							// #endif
							
							// #ifdef APP-PLUS
							// App平台
							this.handleWechatAuth(32, 'app');
							// #endif
						}
					},
				});	
			},
			
			// 处理微信授权登录
			// TODO：这里不应该使用微信登录，应该调用绑定微信的接口，但是后端不配合只能这样
			handleWechatAuth(socialType, state) {
				uni.login({
					provider: 'weixin',
					onlyAuthorize: true,
					success: (loginRes) => {
						// 获取授权code，小程序和App获取方式不同
						const code = loginRes.code || 
							(loginRes.authResult && loginRes.authResult.code ? 
							loginRes.authResult.code : '');
						
						if (!code) {
							const errMsg = loginRes.errMsg || JSON.stringify(loginRes);
							uni.$u.toast('微信登录失败: ' + errMsg)
						}
						
						// 调用后端接口
						this.$http_api.wechatLogin({
							type: socialType,
							code: code,
							state: state
						}).then(res => {
							this.handleLoginSuccess(res)
						})
					},
					fail: (err) => {
						uni.showModal({
							title: '取消授权',
						})
					}
				});
			},
			
			// 处理登录成功
			handleLoginSuccess(data) {
				this.$http_api.userInfo({}).then((res)=>{
					this.$store.dispatch('userLoginAction', res)
					uni.setStorageSync('token', data.accessToken);
					this.handlePayment();
				})
			},
			
			async bind() {
				const codeResult = await uni.login();
				if (codeResult.errMsg !== 'login:ok') {
					return uni.$u.toast('授权失败')
				}
				this.$http_api.wechatBindAccout({
					type: 34,
					code: codeResult.code,
					state: 'default'
				}).then(res => {
					this.$http_api.userInfo({}).then((res)=>{
						this.memberinfo = res;
						this.$store.dispatch('userLoginAction', res)
					})
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.pay-container {
		min-height: 650rpx;

		.pay-header {
			text-align: center;
			padding: 30rpx;
			font-weight: 400;
			font-size: 31rpx;
			color: #333333;
		}

		.pay-amount {
			font-weight: 400;
			font-size: 72rpx;
			color: #FE6601;
			font-style: normal;
			text-transform: none;
			text-align: center;
			display: flex;
			align-items: baseline;
			justify-content: center;

			.yuan {
				font-size: 40rpx;
				padding-right: 15rpx;
			}
		}

		.pay-list {
			min-height: 300rpx;
			.pay-list-item {
				display: flex;
				justify-content: space-between;
				padding: 30rpx 30rpx;
				border-bottom: 1rpx solid #eeeeee;
				
				&.disabled {
					opacity: 0.5;
					cursor: not-allowed;
				}
				
				.pay-item-left {
					.wallet-balance {
						font-size: 24rpx;
						color: #999;
						margin-top: 8rpx;
						
						&.insufficient {
							color: #ff4d4f;
						}
					}
				}
			}
		}

		.pay-btn {
			width: 80%;
			height: 95rpx;
			background: #1C6EFB;
			border-radius: 43rpx;
			font-weight: 400;
			font-size: 28rpx;
			color: #FFFFFF;
			text-align: center;
			line-height: 95rpx;
			margin: 50rpx auto;
		}
	}
</style>